const User = require("../model/system/User");
const JWT = require("../util/jwt");
const config = require("../config/config");

exports.login = async (req, res, next) => {
  try {
    const user = req.user.toJSON();
    delete user.password;
    const token = await JWT.sign(
      {
        userId: user._id,
      },
      config.jwt.secret,
      {
        expiresIn: config.jwt.expiresIn,
      }
    );
    res.status(200).json({
      code: 200,
      message: "登录成功",
      data: {
        token,
        ...user,
      },
    });
  } catch (error) {
    next(error);
  }
};

exports.register = async (req, res, next) => {
  try {
    // 1.获取请求体
    // 2.数据验证   基础数据验证 业务数据验证
    const user = new User(req.body.user);
    const result = await user.save();
    // 3.数据存储
    // 4.返回响应
    res.status(201).json({
      code: 200,
      message: "注册成功",
      data: result,
    });
  } catch (error) {
    next(error);
  }
};

exports.getCurrent = async (req, res, next) => {
  try {
    const user = req.user;
    res.status(200).json({
      code: 200,
      message: "获取用户信息成功",
      data: user,
    });
  } catch (error) {
    next(error);
  }
};
